
import {Injectable} from "@angular/core";
import {Sell} from "../../../shared/model/product/entity/sell";

@Injectable()
export class CartService {
    private _orders: any = [];
    constructor() {
    }

    get orders() {
        return this._orders;
    }

    add(product) {
        if (!this.has(product)) {
            this._orders.push({
                product: product,
                amount: 1,
                price: product.price
            });
        }
    }

    remove(product) {
        const index = this._orders.findIndex(item => item.product === product);
        index != -1 && this._orders.splice(index, 1);
    }

    has(product) {
        return this._orders.find(item => item.product === product);
    }

    clear() {
        this._orders = [];
    }

    out() {
        this._orders.forEach(order => {
           order.product.amount -= order.amount;
        });
        this._orders = [];
    }

    count() {
        return this._orders.length;
    }

    total() {
        return this._orders.reduce((acc, cur) => {
            return acc + cur.price * cur.amount;
        },0);
    }

    check() {
        return this._orders.every(order => order.amount <= order.product.amount);
    }

    commit(customer) {
        return this._orders.map(order => {
            const sell = new Sell();
            sell.product = order.product;
            sell.price = order.price;
            sell.amount = order.amount;
            sell.customer = customer;
            return sell;
        })
    }
}
